package controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class UploadController {
    @Autowired
    private ServletContext application;

//    @Value("${uploadDir}")
//    private String uploadDir;

//    @RequestMapping("/fileupload")
    @RequestMapping("/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file) throws IOException {
        System.out.println("UploadController.upload()");
        System.out.println("f.getName() = " + file.getName());
        System.out.println("f.getContentType() = " + file.getContentType());
        System.out.println("f.getOriginalFilename() = " + file.getOriginalFilename());
        System.out.println("f.getSize() = " + file.getSize());

//        InputStream in=file.getInputStream();

//        file.transferTo(new File("E:/upload",file.getOriginalFilename()));

//        String uploadDir=application.getRealPath("WEB-INF/upload");
//        file.transferTo(new File(uploadDir,file.getOriginalFilename()));

        String rootPath=this.getClass().getClassLoader().getResource("").getPath();
        System.out.println(rootPath);
        String uploadDir=rootPath.substring(0,rootPath.lastIndexOf("/WEB-INF"))+"/WEB-INF/upload";
        System.out.println("uploadDir = " + uploadDir);
        file.transferTo(new File(uploadDir,file.getOriginalFilename()));


        return "redirect:/showUpload";
    }
}
